package cn.hjc.service;

import cn.hjc.dao.HibernateUtil;
import cn.hjc.dao.UserDao;
import cn.hjc.entity.User;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

public class UserBiz {
    private UserDao userDao = new UserDao();

    public User findDeptById(Short id) {
        Transaction tx = null;
        User result = null;
        try {
            tx = HibernateUtil.currentSession().beginTransaction();//开启事务

            //   result = deptDao.get(id);//调用Dao方法，根据OID加载指定Dept对象
            //输出结果，与调用get()方法时不同
            //原因会在后续章节中有关延迟加载的内容中进行分析
            result = userDao.load(id);
            System.out.println(result.getName());
            tx.commit();//提交事务

        } catch (HibernateException e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback(); //回滚事务
        }
        return result;
    }

    public void addNewDept(User dept) {
        Transaction tx = null;
        try {
            tx = userDao.currentSession().beginTransaction();//开启事务
            userDao.save(dept);//提交事务
            tx.commit();//提交事务
        } catch (HibernateException e) {
            e.printStackTrace();
            if (tx != null) {
                tx.rollback();//回滚事务
            }
        }
    }


    public void updateDept(User dept) {
        Transaction tx = null;
        try {
            tx = userDao.currentSession().beginTransaction();//开启事务
            //通过get()或load()方法加载要修改的部门对象
            User deptToUpdate = userDao.load(dept.getId());
            //更新部门数据
            deptToUpdate.setName(dept.getName());
            deptToUpdate.setLocation(dept.getLocation());
            tx.commit();//提交事务

        } catch (HibernateException e) {
            e.printStackTrace();
            if (tx != null)
                tx.rollback();  //回滚事务
        }
    }
    public  void deleteDept(Short id){
        Transaction tx = null;
        try {
            tx = userDao.currentSession().beginTransaction();   //开启事务
            //通过get()或load()方法加载要删除的部门对象
            User deptToDelete = userDao.load(id);
            userDao.delete(deptToDelete);   //删除部门数据
            tx.commit();//提交事务
        }catch (HibernateException e){
            e.printStackTrace();
            if(tx !=null)
                tx.rollback();//回滚事务
        }
    }

    public User mergeDept(User dept){
        Transaction tx = null;
        User persistentDept = null;
        try {
            tx = userDao.currentSession().beginTransaction();//开启事务
            //合并dept的数据或包车dept的副本，返回持久态对象
            persistentDept = userDao.merge(dept);
            tx.commit();
        }catch (HibernateException e){
            e.printStackTrace();
            if(tx !=null)
                tx.rollback();
        }
        return persistentDept;
    }
}
